package cn.touna.jss.modules.third.dianhuabang.utils;

import java.io.*;
import java.util.zip.Deflater;
import java.util.zip.GZIPOutputStream;

public class GZipUtil {

    public static final int BUFFER = 1024;
    public static final String EXT = ".gz";


    public static void compressGzip(String inputFileName, String outputFileName)
            throws Exception {
        FileInputStream inputFile = new FileInputStream(inputFileName);
        FileOutputStream outputFile = new FileOutputStream(outputFileName);
        compress(inputFile, outputFile);
        inputFile.close();
        outputFile.flush();
        outputFile.close();
    }

    public static void compressDeflate(String inputFileName, String outputFileName) throws Exception {
        FileInputStream inputFile = new FileInputStream(inputFileName);
        FileOutputStream outputFile = new FileOutputStream(outputFileName);
        ByteArrayOutputStream inputByte =new ByteArrayOutputStream();
        byte[] data = new byte[BUFFER];
        int count;
        while ((count = inputFile.read(data)) != -1){
            inputByte.write(data,0,count);
        }

        byte[] result = compress(inputByte.toByteArray());
        inputFile.close();
        outputFile.write(result);
        outputFile.flush();
        outputFile.close();
    }

    /**
     * gzip压缩
     * @param is
     * @param os
     * @throws Exception
     */
    public static void compress(InputStream is, OutputStream os)
            throws Exception {

        GZIPOutputStream gos = new GZIPOutputStream(os);
        int count;
        byte data[] = new byte[BUFFER];
        while ((count = is.read(data, 0, BUFFER)) != -1) {
            gos.write(data, 0, count);
        }
        gos.finish();
        gos.flush();
        gos.close();
    }

    public static String compress(String str) throws IOException {
        if (str == null || str.length() == 0) {
            return str;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        gzip.write(str.getBytes());
        gzip.close();
        return out.toString("ISO-8859-1"); // UTF-8 ISO-8859-1

    }

    public static byte[] compress(byte[] inputByte) throws IOException {
        int len = 0;
        Deflater defl = new Deflater();
        defl.setInput(inputByte);
        defl.finish();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] data = new byte[BUFFER];
        while(!defl.finished()){
            // 压缩并将压缩后的内容输出到字节输出流bos中
            len = defl.deflate(data);
            bos.write(data,0,len);

        }
        bos.flush();
        bos.close();
        return bos.toByteArray();
    }
}
